import React, { Component } from 'react';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import { connect } from 'dva';
import {
  Card,
  message,
  Tooltip,
  Button,
  Form,
  Input,
  Select,
  DatePicker,
  Radio,
  Modal,
  Descriptions,
  Divider,
  Upload,
  Icon,
  Tabs,
  Spin,
  Popconfirm,
} from 'antd';
import axios from 'axios';
import MyPageTable from '@/components/MyPageTable';
import { onTableData } from '@/utils/utils.js';
import { uploadUrl } from '@/config/index';
import IpaIndex from './ipaIndex.jsx';
import GuestComplaint from './GuestComplaint.jsx';
import { getParam } from '@/utils/utils';
function getToken() {
  const token = localStorage.getItem('token');
  return token;
}
import moment from 'moment';
const { Option } = Select;
const { RangePicker } = DatePicker;
const { TextArea } = Input;
const { TabPane } = Tabs;
import { router } from 'umi';
function callback(key) {
  console.log(key);
}
@connect(({ batch, loading }) => ({
  ...batch,
  queryTribeCommentPage: loading.effects['batch/queryTribeCommentPage'],
  queryProductEvaluationPage: loading.effects['batch/queryProductEvaluationPage'],
}))
@Form.create()
export default class Comment extends Component {
  state = {
    current: 1,
    visible: false,
    title: null,
    fileLists: [],
    TabsData: '1',
    datas: {},
    channelData: [],
    dataId: {},
    Lists: [],
  };
  componentDidMount() {
    this.onList(1, 10);
    this.props.dispatch({
      type: 'order/PlateformChannel',
      payload: {},
      callback: res => {
        this.setState({
          channelData: res.data,
        });
      },
    });
  }

  onList = (pageNumber, pageSize, data = {}) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'batch/queryTribeCommentPage',
      payload: {
        pageSize,
        pageNumber,
        ...data,
      },
      callback: res => {
        this.setState({
          Lists: res.data.records,
        });
      },
    });
  };
  onList2 = (pageNumber, pageSize, data = {}) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'batch/queryProductEvaluationPage',
      payload: {
        pageSize,
        pageNumber,
        ...data,
      },
    });
  };

  handleSubmit = e => {
    e.preventDefault();
    this.props.form.validateFields((err, values) => {
      if (!err) {
        const { TabsData } = this.state;
        this.setState(
          {
            datas: { ...values },
          },
          () => {
            if (TabsData === '2') {
              let spotvalues = {
                productName: values.resourceName,
                userName: values.name,
                status: values.status,
              };
              this.onList2(1, 10, { ...spotvalues });
            } else {
              this.onList(1, 10, { ...values });
            }
          },
        );
      }
    });
  };
  //table 页数
  onPage = e => {
    const { datas, TabsData } = this.state;
    this.setState(
      {
        current: e.current,
      },
      () => {
        if (TabsData === '2') {
          this.onList2(e.current, 10, { ...datas });
        } else {
          this.onList(e.current, 10, { ...datas });
        }
      },
    );
  };
  //状态
  onRB = (e, record, i) => {
    console.log('进来 来 来来来');
    if (this.state.TabsData === '2') {
      this.props.dispatch({
        type: 'batch/batchEffectProductEvaluation',
        payload: {
          ids: [record.id],
          status: e.target.value,
        },
        callback: res => {
          this.onList2(this.state.current, 10, { ...this.state.datas });
          this.setState({
            visible: false,
          });
        },
      });
    } else {
      this.props.dispatch({
        type: 'batch/batchEffectUserComment',
        payload: {
          ids: [record.id],
          status: e.target.value,
        },
        callback: res => {
          this.onList(this.state.current, 10, { ...this.state.datas });
          this.setState({
            visible: false,
          });
        },
      });
    }
  };
  showModal = (e, id) => {
    const { datas, TabsData } = this.state;
    const { dispatch } = this.props;
    if (e === '编辑评论') {
      this.setState({
        dataId: id,
      });
      if (TabsData === '2') {
        dispatch({
          type: 'batch/selectExamineProductEdit',
          payload: {
            id: id.id,
          },
        });
      } else {
        dispatch({
          type: 'batch/selectTribeCommentEdit',
          payload: {
            id: id.id,
          },
        });
      }
    }

    this.setState({
      visible: true,
      title: e,
      fileLists: [],
    });
  };
  onTabs = e => {
    this.props.form.resetFields();
    this.setState(
      {
        TabsData: e,
        current: 1,
      },
      () => {
        if (e === '2') {
          this.onList2(1, 10);
        } else {
          this.onList(1, 10);
        }
      },
    );
  };
  handleOk = e => {
    e.preventDefault();
    const { title, dataId, TabsData, fileLists } = this.state;
    const { dispatch } = this.props;
    this.props.form.validateFields((err, values) => {
      // if (!err) {
      console.log('Received values of form: ', values);
      if (title === '编辑评论') {
        if (TabsData === '2') {
          dispatch({
            type: 'batch/confirmProductEvaluation',
            payload: {
              id: dataId.id,
              parentId: dataId.parentId,
              channel: values.channel,
              content: values.beizhu,
              status: values.status1,
            },
            callback: res => {
              message.success('编辑成功～');
              this.setState({
                visible: false,
              });
            },
          });
        } else {
          dispatch({
            type: 'batch/confirmTribeCommment',
            payload: {
              id: dataId.id,
              parentId: dataId.parentId,
              channel: values.channel,
              content: values.beizhu,
              status: values.status1,
            },
            callback: res => {
              message.success('编辑成功～');
              this.setState({
                visible: false,
              });
            },
          });
        }
      } else if (title === '批量操作') {
        console.log('批量操作进来了');
        const { List } = this.props;
        let idss = [];
        for (let i = 0; i < List.length; i++) {
          idss.push(List[i].id);
        }

        if (TabsData === '2') {
          dispatch({
            type: 'batch/batchEffectProductEvaluation',
            payload: {
              ids: idss,
              status: values.pinglstatus,
            },
            callback: res => {
              this.onList2(this.state.current, 10, { ...this.state.datas });
              this.setState({
                visible: false,
              });
            },
          });
        } else {
          dispatch({
            type: 'batch/batchEffectUserComment',
            payload: {
              ids: idss,
              status: values.pinglstatus,
            },
            callback: res => {
              this.onList(this.state.current, 10, { ...this.state.datas });
              this.setState({
                visible: false,
              });
            },
          });
        }
      } else {
        if (fileLists.length < 1) {
          message.warning('请上传评论～');
        } else {
          if (TabsData === '2') {
            dispatch({
              type: 'batch/importProductEvaluation',
              payload: {
                url: fileLists[0].response.data,
              },
              callback: res => {
                this.onList2(this.state.current, 10, { ...this.state.datas });
                this.setState({
                  visible: false,
                });
                message.success('导入成功～');
              },
            });
          } else {
            dispatch({
              type: 'batch/importUserComment',
              payload: {
                url: fileLists[0].response.data,
              },
              callback: res => {
                this.onList(this.state.current, 10, { ...this.state.datas });
                this.setState({
                  visible: false,
                });
                message.success('导入成功～');
              },
            });
          }
        }
      }
      // }
    });
  };

  handleCancel = e => {
    console.log(e);
    this.setState({
      visible: false,
    });
  };
  onUpload = info => {
    console.log(info, 'info');
    if (info.fileList.length === 0) {
      this.setState({
        fileLists: [],
      });
    } else {
      this.setState({
        fileLists: [info.fileList[info.fileList.length - 1]],
      });
    }
  };
  onEit = () => {
    if (this.state.TabsData === '2') {
      this.props.dispatch({
        type: 'batch/exportProductEvaluation',
        payload: {},
      });
    } else {
      this.props.dispatch({
        type: 'batch/exportUserComment',
        payload: {},
      });
    }
  };
  onDelt = e => {
    if (this.state.TabsData === '2') {
      this.props.dispatch({
        type: 'batch/deleteProductEvaluation',
        payload: { id: e.id },
        callback: res => {
          this.onList2(this.state.current, 10, { ...this.state.datas });
        },
      });
    } else {
      this.props.dispatch({
        type: 'batch/deleteUserComment',
        payload: { id: e.id },
        callback: res => {
          this.onList(this.state.current, 10, { ...this.state.datas });
        },
      });
    }
  };
  onexport = () => {
    if (this.state.TabsData === '2') {
      this.props.dispatch({
        type: 'batch/exportProductEvaluationMessage',
        payload: { pageSize: 10, pageNumber: this.state.current, ...this.state.datas },
        callback: res => {
          location.href = res.data;
        },
      });
    } else {
      this.props.dispatch({
        type: 'batch/exportUserCommentMessage',
        payload: { pageSize: 10, pageNumber: this.state.current, ...this.state.datas },
        callback: res => {
          location.href = res.data;
        },
      });
    }
  };

  handleReset = e => {
    this.props.form.resetFields();
    this.props.form.setFieldsValue({
      // status: undefined,
      // type: undefined,
    });
    this.handleSubmit(e);
  };

  handleChange = file => {
    let formdata = new FormData();
    formdata.append('file', file);
    console.log('formdata:', formdata);
    console.log('file:', file);
  };
  render() {
    const { List, Total, EditData } = this.props;
    const paginationProps = {
      current: this.state.current,
      pageSize: 10,
      total: Total,
      showTotal: total => (
        <span style={{ fontSize: '14px' }}>
          <span>共{Math.ceil(total / 10)}页</span>&emsp;
          <span>共{total}条</span>
        </span>
      ),
    };
    // batchEffectUserComment
    const columns = [
      {
        title: '评论标题ID',
        dataIndex: 'id',
        width: '10%',
      },
      {
        title: '评论标题名称',
        dataIndex: 'resourceName',
        width: '10%',
      },
      {
        title: '评论人',
        dataIndex: 'name',
        width: '10%',
      },
      {
        title: '评论内容',
        dataIndex: 'content',
        width: '10%',
      },
      {
        title: '上架渠道',
        dataIndex: 'channelName',
        width: '10%',
      },
      {
        title: '评论时间',
        dataIndex: 'createTime',
        width: '10%',
      },
      {
        title: '回复状态',
        dataIndex: 'azContent',
        width: '10%',
        render: azContent => {
          return (
            <>
              {azContent ? (
                <Tooltip placement="top" title={azContent}>
                  <Button type="link">
                    已回
                    <Icon type="message" />
                  </Button>
                </Tooltip>
              ) : (
                <Button type="link">未回</Button>
              )}
            </>
          );
        },
      },

      {
        title: '评论状态',
        // dataIndex: 'status',
        width: '20%',
        render: record => {
          return (
            <Radio.Group
              buttonStyle="solid"
              onChange={e => this.onRB(e, record, '评论状态')}
              value={record.status}
            >
              <Radio.Button value={0}>显示</Radio.Button>
              <Radio.Button value={1}>不显示</Radio.Button>
            </Radio.Group>
          );
        },
      },
      {
        title: '操作',
        width: '10%',
        render: e => {
          return (
            <div>
              <span
                style={{ cursor: 'pointer', color: '#3F66F5', marginRight: 7 }}
                onClick={() => this.showModal('编辑评论', e)}
              >
                查看
              </span>
              <Popconfirm title="确定删除吗？" onConfirm={() => this.onDelt(e)}>
                <span style={{ cursor: 'pointer', color: '#3F66F5' }}>删除</span>
              </Popconfirm>
            </div>
          );
        },
      },
    ];
    const { getFieldDecorator } = this.props.form;
    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 4 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 18 },
      },
    };
    const { fileLists } = this.state;
    return (
      <PageHeaderWrapper>
        <Card bordered={false}>
          <Tabs defaultActiveKey={getParam('See') ? '4' : '1'} onChange={this.onTabs}>
            <TabPane tab="部落评论" key="1">
              <Form layout="inline" onSubmit={this.handleSubmit}>
                <Form.Item label={'评论标题名称'}>
                  {getFieldDecorator(
                    'resourceName',
                    {},
                  )(<Input placeholder="请输入评论标题名称" />)}
                </Form.Item>
                <Form.Item label={'评论人'}>
                  {getFieldDecorator('name', {})(<Input placeholder="请输入评论人" />)}
                </Form.Item>
                <Form.Item label={'评论状态'}>
                  {getFieldDecorator(
                    'status',
                    {},
                  )(
                    <Select placeholder="评论状态" style={{ width: 180 }}>
                      <Option value="">全部</Option>
                      <Option value={0}>显示</Option>
                      <Option value={1}>不显示</Option>
                    </Select>,
                  )}
                </Form.Item>
                <Form.Item>
                  <Button type="primary" htmlType="submit">
                    查询
                  </Button>
                </Form.Item>
                <Form.Item>
                  <Button htmlType="button" onClick={this.handleReset}>
                    重置
                  </Button>
                </Form.Item>
                <Form.Item>
                  <Button onClick={() => this.onexport()}>导出</Button>
                </Form.Item>
              </Form>
              <Button
                type="primary"
                style={{
                  margin: '30px 0',
                  marginRight: 30,
                }}
                onClick={() => this.showModal('批量操作')}
              >
                批量操作
              </Button>
              <Button onClick={() => this.showModal('导入评论')}>导入评论</Button>
              <Spin spinning={this.props.queryTribeCommentPage}>
                <MyPageTable
                  onPage={this.onPage}
                  paginationProps={paginationProps}
                  dataSource={onTableData(List)}
                  columns={columns}
                />
              </Spin>
            </TabPane>
            <TabPane tab="商品评论" key="2">
              <Form layout="inline" onSubmit={this.handleSubmit}>
                <Form.Item>
                  {getFieldDecorator(
                    'resourceName',
                    {},
                  )(<Input placeholder="请输入评论标题名称" />)}
                </Form.Item>
                <Form.Item>
                  {getFieldDecorator('name', {})(<Input placeholder="请输入评论人" />)}
                </Form.Item>
                <Form.Item>
                  {getFieldDecorator(
                    'status',
                    {},
                  )(
                    <Select placeholder="评论状态" style={{ width: 180 }}>
                      <Option value="">全部</Option>
                      <Option value={0}>显示</Option>
                      <Option value={1}>不显示</Option>
                    </Select>,
                  )}
                </Form.Item>
                <Form.Item>
                  <Button type="primary" htmlType="submit">
                    查询
                  </Button>
                </Form.Item>
                <Form.Item>
                  <Button onClick={() => this.onexport()}>导出</Button>
                </Form.Item>
              </Form>
              <Button
                type="primary"
                style={{
                  margin: '30px 0',
                  marginRight: 30,
                }}
                onClick={() => this.showModal('批量操作')}
              >
                批量操作
              </Button>
              <Button onClick={() => this.showModal('导入评论')}>导入评论</Button>
              <Spin spinning={this.props.queryProductEvaluationPage}>
                <MyPageTable
                  onPage={this.onPage}
                  paginationProps={paginationProps}
                  dataSource={onTableData(List)}
                  columns={columns}
                />
              </Spin>
            </TabPane>
            <TabPane tab="小程序评论" key="3">
              <IpaIndex />
            </TabPane>
            <TabPane tab="客诉" key="4">
              <GuestComplaint />
            </TabPane>
            {/* GuestComplaint */}
          </Tabs>
        </Card>
        <Modal
          title={this.state.title}
          visible={this.state.visible}
          onOk={this.handleOk}
          onCancel={this.handleCancel}
          destroyOnClose
        >
          {this.state.title === '编辑评论' ? (
            <>
              <Descriptions>
                <Descriptions.Item label="标题" span={3}>
                  {EditData && EditData.resourceName}
                </Descriptions.Item>
                <Descriptions.Item label="内容" span={3}>
                  <div
                    dangerouslySetInnerHTML={{ __html: EditData && EditData.resourceContent }}
                  ></div>
                </Descriptions.Item>
              </Descriptions>
              <Divider />
              <Descriptions>
                <Descriptions.Item label="评论人" span={3}>
                  {EditData && EditData.name}
                  {EditData && EditData.userName}
                </Descriptions.Item>
                <Descriptions.Item label="评论内容" span={3}>
                  {EditData && EditData.content}
                </Descriptions.Item>
                <Descriptions.Item label="评论时间" span={3}>
                  {EditData && EditData.createTime}
                </Descriptions.Item>
              </Descriptions>
              <Divider />
              <Form {...formItemLayout}>
                <Form.Item label="状态">
                  {getFieldDecorator('status1', {
                    initialValue: EditData && EditData.status,
                  })(
                    <Radio.Group>
                      <Radio value={0}>显示</Radio>
                      <Radio value={1}>不显示</Radio>
                    </Radio.Group>,
                  )}
                </Form.Item>
                <Form.Item label="上架渠道">
                  {getFieldDecorator('channel', {
                    initialValue: EditData && EditData.channel && EditData.channel.split('&'),
                  })(
                    <Select
                      placeholder="评论状态"
                      style={{ width: 180 }}
                      mode="multiple"
                      style={{ width: '100%' }}
                    >
                      {this.state.channelData.map((item, sign) => {
                        return (
                          <Option key={item.channelId} value={item.channelId}>
                            {item.channelName}
                          </Option>
                        );
                      })}
                    </Select>,
                  )}
                </Form.Item>
                <Form.Item label="客服回复">
                  {getFieldDecorator('beizhu', {
                    initialValue: EditData && EditData.azContent,
                  })(<TextArea placeholder="请输入" />)}
                </Form.Item>
              </Form>
            </>
          ) : this.state.title === '批量操作' ? (
            <>
              <Form {...formItemLayout}>
                <Form.Item label="评论状态">
                  {getFieldDecorator('pinglstatus', {
                    initialValue: 0,
                  })(
                    <Radio.Group>
                      <Radio value={0}>显示</Radio>
                      <Radio value={1}>不显示</Radio>
                    </Radio.Group>,
                  )}
                </Form.Item>
              </Form>
            </>
          ) : this.state.title === '导入评论' ? (
            <Form.Item {...formItemLayout} label="上传" required>
              <Button style={{ width: '104px', height: '31px', marginRight: 30 }}>
                {/* <a style={{ textDecoration: 'none' }} href={testModal} download="模版">下载模板</a> */}
                <a style={{ textDecoration: 'none' }} download="模版" onClick={() => this.onEit()}>
                  下载模板
                </a>
              </Button>
              <Upload
                fileList={fileLists}
                onChange={this.onUpload}
                // beforeUpload={file => {
                //   this.handleChange(file);
                //   return false;
                // }}
                action={uploadUrl}
                headers={{
                  token: getToken(),
                }}
              >
                <Button type="primary" ghost>
                  <Icon type="upload" /> 上传评论
                </Button>
              </Upload>
            </Form.Item>
          ) : null}
        </Modal>
      </PageHeaderWrapper>
    );
  }
}
